﻿using System;
using System.Collections.Generic;

namespace SimpleServiceBus.Utilities.ObjectBuilder
{
    public class DefaultObjectBuilder : IObjectBuilder
    {
        private readonly Dictionary<Type, object> _singleton = new Dictionary<Type, object>();

        public T Build<T>()
        {
            return (T)Build(typeof(T));
        }

        public object Build(Type typeToBuild)
        {
            if (typeToBuild == null)
                throw new ArgumentNullException("typeToBuild");
            
            object built = TryBuild(typeToBuild);
            if (built == null)
                throw new InvalidOperationException(typeToBuild.Name + " cannot be constructed by the Object Builder.");
            
            return built;
        }

        public T TryBuild<T>()
        {
            return (T)TryBuild(typeof(T));
        }

        public virtual object TryBuild(Type typeToBuild)
        {
            if (_singleton.ContainsKey(typeToBuild))
                return _singleton[typeToBuild];

            if (typeToBuild.IsInterface || typeToBuild.IsAbstract)
                return null;

            return Activator.CreateInstance(typeToBuild);  
        }

        public void RegisterSingleton<TSingletonType>(TSingletonType singleton)
        {
            _singleton[typeof(TSingletonType)] = singleton;
        }
    }
}
